package com.hyk.learning.remoting.transport.socket;

import com.hyk.learning.dto.RpcRequest;
import com.hyk.learning.dto.RpcResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;

/**
 * @className: HelloClient
 * @author: hyk199710
 * @description: TODO
 * @date: 2024/4/14 22:27
 */
public class HelloClient {

    private static final Logger logger = (Logger) LoggerFactory.getLogger(HelloClient.class);

    public Object send(RpcRequest rpcRequest, String host, int port) {
        try (Socket socket = new Socket(host, port)) {
            ObjectOutputStream objectOutputStream = new ObjectOutputStream(socket.getOutputStream());
            objectOutputStream.writeObject(rpcRequest);
            ObjectInputStream objectInputStream = new ObjectInputStream(socket.getInputStream());
            return objectInputStream.readObject();
        } catch (IOException | ClassNotFoundException e) {
            logger.error("occur exception:", e);
        }
        return null;
    }

    public static void main(String[] args) {
        HelloClient helloClient = new HelloClient();
        RpcRequest rpcRequest = new RpcRequest();
        RpcResponse<String> rpcResponse = (RpcResponse) helloClient.send(rpcRequest, "127.0.0.1", 6666);
        System.out.println("client receive message:" + rpcResponse.getData());
    }

}
